﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Framework.ProviderLoader;
using PSE.Framework.ProviderLoader.Configuration;
using PSE.ProcessManager.Entity;
using System.Configuration;
using System.IO;

namespace PSE.ProcessManager.ResourceAccess.FileSystemProvider
{
    public class InstanceConfigurationResourceAccess : BaseProvider, IInstanceConfigurationResourceAccess
    {
        private static string _baseFilePath;

        static InstanceConfigurationResourceAccess()
        {
            _baseFilePath = Path.GetDirectoryName(System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
        }

        public InstanceConfigurationResourceAccess(ProviderConfigurationElement configuration)
            : base(configuration)
        {
        }

        #region IInstanceConfigurationResourceAccess Members

        private string GetFilePath(string productId)
        {
            return _baseFilePath + @"\Instances\" + productId + @"\Instances.config";
        }

        public List<InstanceEntity> RetrieveInstances(string produtctId)
        {
            string filePath = GetFilePath(produtctId);
            if (!File.Exists(filePath))
                return null;
            else
            {
                PSE.Framework.Serialization.XmlSerializer ser = new PSE.Framework.Serialization.XmlSerializer(typeof(List<InstanceEntity>));
                return ser.DeserializeFromFile<List<InstanceEntity>>(filePath);
            }
        }

        public void SaveInstances(string produtctId, List<InstanceEntity> instances)
        {
            string filePath = GetFilePath(produtctId);
            PSE.Framework.Serialization.XmlSerializer ser = new PSE.Framework.Serialization.XmlSerializer(typeof(List<InstanceEntity>));
            ser.SerializeToFile(filePath, instances);
        }
        #endregion
    }
}
